<?php

class ExcelToArray{
	public function __construct() {
		include_once('./Classes/PHPExcel.php');
		include_once('./Classes/PHPExcel/IOFactory.php');
	}

    /**
     * 读excel文件（linux的LibreOffice Calc下的文件不能读取）
     * @param $file 文件路径和文件名组成的字符串
     * @return array
     */
	public static function read($file){
		$objRead = new PHPExcel_Reader_Excel2007();   //建立reader对象  
		if(!$objRead->canRead($file)){  
			$objRead = new PHPExcel_Reader_Excel5();  
			if(!$objRead->canRead($file)){  
				die('No Excel!');  
			}  
		}

		$obj = $objRead->load($file);  //建立excel对象  
		$currSheet = $obj->getActiveSheet();   
		$columns = $currSheet->getHighestColumn();   //取得总列数 
		$colNumber = PHPExcel_Cell::columnIndexFromString($columns);
		$rows = $currSheet->getHighestRow();		 //获取总行数  
		$data = array();
		for ($row = 2; $row <= $rows; $row++) {
			for ($column = 0; $column <= $colNumber-1; $column++) {
				$val = $currSheet->getCellByColumnAndRow($column, $row)->getValue();
				$data[$row][$column] = $val;
			}
		}
		return $data; 
	}
	
	/**
	 *导出excel(phpexcel)
	 *
	 */
	public function phpexcelExport()
	{

	}

	/**
	 *导出excel(通过html实现)
	 *@param $data array 设置数据
	 *@param $titlename  
	 *@param $title
	 *@param $filename
	 */
	public function htmlExport($data,$titlename,$title,$filename)
	{
		$str = "<html xmlns:o=\"urn:schemas-microsoft-com:office:office\"\r\nxmlns:x=\"urn:schemas-microsoft-com:office:excel\"\r\nxmlns=\"http://www.w3.org/TR/REC-html40\">\r\n<head>\r\n<meta http-equiv=Content-Type content=\"text/html; charset=utf-8\">\r\n</head>\r\n<body>"; 
		$str .="<table border=1><head>".$titlename."</head>"; 
		$str .= $title;
		foreach ($data  as $key=> $rt ) 
		{ 
			$str .= "<tr>"; 
			foreach ( $rt as $k => $v ) 
			{ 
				$str .= "<td>{$v}</td>"; 
			} 
			$str .= "</tr>\n"; 
		} 
		$str .= "</table></body></html>"; 
		header( "Content-Type: application/vnd.ms-excel; name='excel'" ); 
		header( "Content-type: application/octet-stream" ); 
		header( "Content-Disposition: attachment; filename=".$filename ); 
		header( "Cache-Control: must-revalidate, post-check=0, pre-check=0" ); 
		header( "Pragma: no-cache" ); 
		header( "Expires: 0" ); 
		exit( $str ); 
	}
}
